package com.example.demo.leetcode.top100;

import java.util.LinkedList;
import java.util.List;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _60单词搜索
 * @description
 * @date 2023/06/21 15:33
 * <p>
 * ******************************************************
 */
public class _60单词搜索 {

    boolean result = false;

    public boolean exist(char[][] board, String word) {
        int m = board.length;
        int n = board[0].length;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (!result) {
                    boolean[][] used = new boolean[m][n];
                    backtrack(board, word, i, j, used);
                }
            }
        }
        return result;
    }

    private void backtrack(char[][] board, String word, int i, int j, boolean[][] used) {
        int m = board.length;
        int n = board[0].length;
        if (result || i < 0 || i >= m || j < 0 || j >= n || used[i][j]) {
            return;
        }

        char c = board[i][j];
        if (c == word.charAt(0)) {
            used[i][j] = true;
            if (word.length() == 1) {
                result = true;
                return;
            }
            // 下
            backtrack(board, word.substring(1), i + 1, j, used);
            // 上
            backtrack(board, word.substring(1), i - 1, j, used);
            // 右
            backtrack(board, word.substring(1), i, j + 1, used);
            // 左
            backtrack(board, word.substring(1), i, j - 1, used);

            used[i][j] = false;
        }
    }

    public static void main(String[] args) {
        _60单词搜索 s = new _60单词搜索();
        System.out.println(s.exist(new char[][]{{'A','B','C','E'},
                {'S','F','E','S'},
                {'A','D','E','E'}}, "ABCESEEEFS"));
    }

}
